import { useUserStoreHook } from "@/store/modules/user";
//进行axios二次封装（请求拦截器和响应拦截器）
import axios, { InternalAxiosRequestConfig } from "axios";
import { ElMessage, ElMessageBox } from "element-plus";

const createService = () => {
  //系统服务
  const systemService = axios.create({
    baseURL: import.meta.env.VITE_APP_SYSTEM_API,
    timeout: 5000,
  });

  // 请求拦截器
  systemService.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
      const userStore = useUserStoreHook();
      if (userStore.token) {
        config.headers.Authorization = userStore.token;
      }
      return config;
    }
  );

  // 响应拦截器
  systemService.interceptors.response.use(
    (response) => {
      // 对响应数据做些处理
      const { code, msg } = response.data;
      if (code === "20000") {
        return response.data;
      }
      // 响应数据为二进制流处理(Excel导出)
      if (response.data instanceof ArrayBuffer) {
        return response;
      }
      ElMessage.error(msg || "系统出错");
      return Promise.reject(new Error(msg || "Error"));
    },
    (error) => {
      // 对响应错误做些处理
      if (error.response.data) {
        const { code, msg } = error.response.data;
        // token 过期,重新登录
        if (code === "A0230") {
          ElMessageBox.confirm("当前页面已失效，请重新登录", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          }).then(() => {
            localStorage.clear();
            window.location.href = "/";
          });
        } else {
          ElMessage.error(msg || "系统出错");
        }
      }
      return Promise.reject(error.message);
    }
  );

  //消息服务
  const messageService = axios.create({
    baseURL: import.meta.env.VITE_APP_MESSAGE_API,
    timeout: 5000,
  });

  messageService.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
      const userStore = useUserStoreHook();
      if (userStore.token) {
        config.headers.Authorization = userStore.token;
      }
      return config;
    }
  );

  messageService.interceptors.response.use(
    (response) => {
      // 对响应数据做些处理
      const { code, message } = response.data;
      if (code == "20000") {
        return response.data;
      }
      // 响应数据为二进制流处理(Excel导出)
      if (response.data instanceof ArrayBuffer) {
        return response;
      }

      ElMessage.error(message || "系统出错");
      return Promise.reject(new Error(message || "Error"));
    },
    (error) => {
      // 对响应错误做些处理
      if (error.response.data) {
        const { code, msg } = error.response.data;
        // token 过期,重新登录
        if (code === "A0230") {
          ElMessageBox.confirm("当前页面已失效，请重新登录", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          }).then(() => {
            localStorage.clear();
            window.location.href = "/";
          });
        } else {
          ElMessage.error(msg || "系统出错");
        }
      }
      return Promise.reject(error.message);
    }
  );

  //资源服务
  const resourceService = axios.create({
    baseURL: import.meta.env.VITE_APP_RESOURCE_API,
    timeout: 5000,
  });

  resourceService.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
      const userStore = useUserStoreHook();
      if (userStore.token) {
        config.headers.Authorization = userStore.token;
      }
      return config;
    }
  );

  resourceService.interceptors.response.use(
    (response) => {
      // 对响应数据做些处理
      const { code, msg } = response.data;
      if (code === "20000") {
        return response.data;
      }
      // 响应数据为二进制流处理(Excel导出)
      if (
        response.data instanceof ArrayBuffer ||
        response.data instanceof Blob
      ) {
        return response;
      }
      if (response.data instanceof Blob) {
        // 返回数据是Blob类型
        // 在此处处理Blob类型数据，比如文件下载、图片展示等
        // 获取文件名
        const contentDisposition = response.headers["content-disposition"];

        const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        const matches = filenameRegex.exec(contentDisposition);
        let finalFilename = "downloaded-file";
        if (matches) {
          const match = matches[1].replace(/['"]/g, "").split("%2F");
          finalFilename = match[match.length - 1];
        }

        // 创建Blob URL并下载
        const blob = new Blob([response.data]);
        console.log(blob.size);
        const blobUrl = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = blobUrl;
        link.download = finalFilename;
        link.target = "_blank";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        // 释放Blob URL资源
        URL.revokeObjectURL(blobUrl);
        return response;
      }
      ElMessage.error(msg || "系统出错");
      return Promise.reject(new Error(msg || "Error"));
    },
    (error) => {
      // 对响应错误做些处理
      if (error.response.data) {
        const { code, msg } = error.response.data;
        // token 过期,重新登录
        if (code === "A0230") {
          ElMessageBox.confirm("当前页面已失效，请重新登录", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          }).then(() => {
            localStorage.clear();
            window.location.href = "/";
          });
        } else {
          ElMessage.error(msg || "系统出错");
        }
      }
      return Promise.reject(error.message);
    }
  );

  //搜索服务
  const esService = axios.create({
    baseURL: import.meta.env.VITE_APP_ES_API,
    timeout: 5000,
  });

  // 请求拦截器
  esService.interceptors.request.use((config: InternalAxiosRequestConfig) => {
    const userStore = useUserStoreHook();
    if (userStore.token) {
      config.headers.Authorization = userStore.token;
    }
    return config;
  });

  // 响应拦截器
  esService.interceptors.response.use(
    (response) => {
      // 对响应数据做些处理
      const { code, msg } = response.data;
      if (code === "20000") {
        return response.data;
      }
      // 响应数据为二进制流处理(Excel导出)
      if (response.data instanceof ArrayBuffer) {
        return response;
      }
      ElMessage.error(msg || "系统出错");
      return Promise.reject(new Error(msg || "Error"));
    },
    (error) => {
      // 对响应错误做些处理
      if (error.response.data) {
        const { code, msg } = error.response.data;
        // token 过期,重新登录
        if (code === "A0230") {
          ElMessageBox.confirm("当前页面已失效，请重新登录", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          }).then(() => {
            localStorage.clear();
            window.location.href = "/";
          });
        } else {
          ElMessage.error(msg || "系统出错");
        }
      }
      return Promise.reject(error.message);
    }
  );

  //搜索服务
  const fileService = axios.create({
    baseURL: import.meta.env.VITE_APP_FILE_API,
    timeout: 5000,
  });

  // 请求拦截器
  fileService.interceptors.request.use((config: InternalAxiosRequestConfig) => {
    const userStore = useUserStoreHook();
    if (userStore.token) {
      config.headers.Authorization = userStore.token;
    }
    return config;
  });

  // 响应拦截器
  fileService.interceptors.response.use(
    (response) => {
      // 对响应数据做些处理
      const { code, msg } = response.data;
      if (code === "20000") {
        return response.data;
      }
      // 响应数据为二进制流处理(Excel导出)
      if (response.data instanceof ArrayBuffer) {
        return response;
      }
      ElMessage.error(msg || "系统出错");
      return Promise.reject(new Error(msg || "Error"));
    },
    (error) => {
      // 对响应错误做些处理
      if (error.response.data) {
        const { code, msg } = error.response.data;
        // token 过期,重新登录
        if (code === "A0230") {
          ElMessageBox.confirm("当前页面已失效，请重新登录", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          }).then(() => {
            localStorage.clear();
            window.location.href = "/";
          });
        } else {
          ElMessage.error(msg || "系统出错");
        }
      }
      return Promise.reject(error.message);
    }
  );

  return {
    systemService,
    messageService,
    resourceService,
    esService,
    fileService,
  };
};

export default createService();
